<template>
	<div class="order-list">
		<div class="card-item" v-for="(order, i) in orderList" :key="order.id || i">
			<van-cell class="card-header" :title="`订单号：${order.order_no || order.id || 'N/A'}`" :label="`订单时间：${order.order_time || order.created_at || 'N/A'}`">
				<template #default>
					<span>{{orderStatus(order)}}</span>
					<span v-if="order.status !== undefined && order.status !== -1 && order.status !== 1" @click="onClickOrderCancel(order.id)">|取消订单</span>
				</template>
			</van-cell>

			<!-- 订单明细列表 -->
			<template v-if="order.detailList && order.detailList.length > 0">
				<van-card 
					v-for="item in order.detailList" 
					:key="item.id || item.orderDetailId" 
					:num="item.count" 
					:price="item.price.toFixed(2)"
					:title="item.product_name" 
					:desc="item.product_spec" 
					:thumb="item.product_pic"
					@click="onClick2OrderDetail(order.id)"
				/>
			</template>
			<template v-else>
				<van-cell title="暂无订单明细" />
			</template>
			<div class="amount">实付金额：<span>¥{{ orderAmount(order) }}</span></div>
		</div>
		
		<!-- 空状态提示 -->
		<div v-if="orderList.length === 0" class="empty-state">
			<van-empty description="暂无订单" />
		</div>
	</div>
</template>

<script>
	import { getOrderListAPI, cancleOrderByIdAPI } from "@/api/order.js";
	import { showToast, showConfirmDialog } from 'vant';
	export default {
		data() {
			return {
				orderList: [],
				APIDomainName: import.meta.env.VITE_APIDomainName || '/', // 接口域名
			};
		},
		//生命周期钩子函数
		created() {
			this.getOrderList();
		},

		methods: {
		//获取订单列表 
		getOrderList() {
			getOrderListAPI().then(result => {
				console.log("订单列表API返回数据:", result); // 调试用
				
				// 根据后端返回结构：R<PageListVo<OrderDetailVo>>
				// PageListVo 包含：list、totalCount、totalPage
				let orders = [];
				if (result.data) {
					// 后端返回的是 PageListVo，包含 list 字段
					if (result.data.list && Array.isArray(result.data.list)) {
						orders = result.data.list;
					}
					// 兼容处理：如果直接是数组
					else if (Array.isArray(result.data)) {
						orders = result.data;
					}
				}
				
				// 映射数据字段，确保与前端期望的格式一致
				// 根据数据库 book_order 表结构：id, order_no, user_id, address_id, amount, remark, status, created_at, updated_at
				// 订单明细通常在关联的订单明细表中，后端应该通过 OrderDetailVo 返回
				this.orderList = orders.map(order => {
					// 处理订单明细列表，支持多种可能的字段名
					let detailList = [];
					if (order.orderItemList) {
						// 后端返回的字段名（最优先）
						detailList = Array.isArray(order.orderItemList) ? order.orderItemList : [];
					} else if (order.detailList) {
						detailList = Array.isArray(order.detailList) ? order.detailList : [];
					} else if (order.detail_list) {
						detailList = Array.isArray(order.detail_list) ? order.detail_list : [];
					} else if (order.items) {
						detailList = Array.isArray(order.items) ? order.items : [];
					} else if (order.orderDetails) {
						detailList = Array.isArray(order.orderDetails) ? order.orderDetails : [];
					} else if (order.orderDetailList) {
						detailList = Array.isArray(order.orderDetailList) ? order.orderDetailList : [];
					} else if (order.order_item_list) {
						detailList = Array.isArray(order.order_item_list) ? order.order_item_list : [];
					} else if (order.goodsList) {
						detailList = Array.isArray(order.goodsList) ? order.goodsList : [];
					} else if (order.goods_list) {
						detailList = Array.isArray(order.goods_list) ? order.goods_list : [];
					}
					
					// 映射订单明细字段（根据订单明细表结构）
					detailList = detailList.map(item => ({
						id: item.id || item.orderDetailId || item.order_detail_id,
						order_id: item.order_id || item.orderId,
						product_id: item.product_id || item.productId,
						product_name: item.product_name || item.productName || item.name || '',
						product_spec: item.product_spec || item.productSpec || item.spec || '',
						product_pic: item.product_pic || item.productPic || item.pic || '',
						price: parseFloat(item.price || 0),
						count: parseInt(item.count || 0)
					}));
					
					return {
						// 订单主表字段（book_order）
						id: order.id || order.orderId,
						order_no: order.order_no || order.orderNo || '',
						user_id: order.user_id || order.userId,
						address_id: order.address_id || order.addressId,
						amount: parseFloat(order.amount || 0),
						remark: order.remark || '',
						status: order.status !== undefined ? parseInt(order.status) : -1,
						// 时间字段映射
						order_time: order.order_time || order.orderTime || order.created_at || order.createdAt || '',
						created_at: order.created_at || order.createdAt || '',
						updated_at: order.updated_at || order.updatedAt || '',
						// 订单明细列表（从订单明细表关联查询得到）
						detailList: detailList
					};
				});
				
				console.log("处理后的订单列表:", this.orderList); // 调试用
			}).catch((error) => {
				console.error("获取订单列表失败:", error);
				showToast("获取订单列表失败");
				this.orderList = [];
			});
		},
			// 触发导航到订单详情（此时该路由功能还没有实现）
			onClick2OrderDetail(id) {
				this.$router.push({
					name: "orderDetail",
					query: {
						id
					}
				});
			},
			// 触发取消订单
			onClickOrderCancel(id) {
				showConfirmDialog({
					message: '确定要取消这个订单吗？'
				}).then(() => {
					//调用接口
					cancleOrderByIdAPI(id).then(() => {
						showToast("订单已取消");
						this.getOrderList();
					}).catch((error) => {
						console.error("取消订单失败:", error);
						showToast("取消订单失败");
					});
				}).catch(() => {
					// 用户取消操作
				});
			},

			//计算一个订单的总金额
			orderAmount(order) {
				if (!order || !order.detailList || order.detailList.length === 0) {
					return '0.00';
				}
				let amount = 0;
				order.detailList.forEach(item => {
					amount += (item.count || 0) * (item.price || 0);
				});
				return amount.toFixed(2);
			},
			//订单状态格式转换
			orderStatus(order) {
				if (!order || order.status === undefined) {
					return "未知";
				}
				let status = "未知";
				switch (order.status) {
					case 0:
						status = "未支付";
						break;
					case 1:
						status = "已支付";
						break;
					case 2:
						status = "已完成";
						break;
					case 3:
						status = "已发货";
						break;
					case -1:
						status = "已取消";
						break;
					default:
						status = `状态${order.status}`;
				}
				return status;
			},
		},
	};
</script>

<style lang="less" scoped>
	// 定义主题色变量（与其他页面保持一致）
	@mainColor: #8b4513; // 棕色主题色
	@bgColor: #f9f5ed; // 米黄色背景
	@lightBrown: #f5e8d0; // 浅棕色
	@darkBrown: #5a4a42; // 深棕色

	.order-list {
		background-color: @bgColor; // 使用主题背景色
		margin-top: 50px;
		min-height: 100vh;
		padding-bottom: 20px;
	}

	.card-item {
		margin: 10px;
		padding: 0;
		background-color: white;
		border-radius: 8px;
		font-size: 16px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		overflow: hidden;
		border-left: 4px solid @mainColor; // 左侧主题色标识线
	}

	.card-header {
		padding: 12px 15px;
		font-size: 16px;
		font-weight: 500;
		display: flex;
		justify-content: space-between;
		background-color: white;
		border-bottom: 1px solid @lightBrown;

		/deep/ .van-cell {
			padding: 0;
			background-color: transparent;
			border: none;
			box-shadow: none;
			margin: 0;
		}

		/deep/ .van-cell__title {
			color: @darkBrown;
			font-weight: 600;
			font-size: 15px;
		}

		/deep/ .van-cell__label {
			color: #666;
			font-size: 13px;
			margin-top: 4px;
		}

		/deep/ .van-cell__value {
			color: @mainColor;
			font-weight: 500;
			font-size: 14px;
			
			span:last-child {
				color: #999;
				font-weight: normal;
				margin-left: 8px;
				cursor: pointer;
				
				&:hover {
					color: @mainColor;
				}
			}
		}
	}

	// 商品卡片样式
	/deep/ .van-card {
		margin: 0;
		padding: 12px 15px;
		border-radius: 0;
		background-color: white;
		border-bottom: 1px solid #f5f5f5;
		border-left: none;
		box-shadow: none;

		&:last-child {
			border-bottom: none;
		}

		.van-card__title {
			font-size: 15px;
			color: @darkBrown;
			font-weight: 500;
		}

		.van-card__desc {
			color: #666;
			font-size: 13px;
		}

		.van-card__price {
			color: #e53935;
			font-weight: bold;
			font-size: 16px;
		}

		.van-card__num {
			color: #666;
			font-size: 14px;
		}
	}

	.amount {
		padding: 12px 15px;
		text-align: right;
		color: @darkBrown;
		font-weight: 600;
		font-size: 16px;
		background-color: @lightBrown; // 使用浅棕色背景
		border-top: 1px solid rgba(139, 69, 19, 0.1);

		span {
			color: #e53935;
			font-size: 18px;
			font-weight: bold;
			margin-left: 5px;
		}
	}
	
	.empty-state {
		padding: 80px 20px;
		text-align: center;
		background-color: @bgColor;
	}
</style>